// This script will be run in the webview
(function () {
    const vscode = acquireVsCodeApi();

    // --- DOM Elements ---
    const commitMessageTextarea = document.getElementById('commit-message');

    // --- State ---
    const statusMap = {
        'M': 'Modified', 'A': 'Added', 'D': 'Deleted', 'R': 'Renamed',
        'C': 'Copied', 'U': 'Unmerged', '?': 'Untracked'
    };

    // --- Helper Functions ---
    function postCommand(command, payload = {}) {
        vscode.postMessage({ command, payload });
    }

    function setActiveTab(tabId, fetchData = true) {
        document.querySelectorAll('.tab-button').forEach(btn => btn.classList.remove('active'));
        document.querySelectorAll('.tab-content').forEach(content => content.style.display = 'none');

        const button = document.getElementById(`tab-${tabId}`);
        if (button) {
            button.classList.add('active');
            const content = document.getElementById(`content-${tabId}`);
            if (content) {
                content.style.display = 'block';
            }
        }

        if (!fetchData) {
            return;
        }

        // Fetch data for the activated tab
        if (tabId === 'workspace') postCommand('getStatus');
        else if (tabId === 'history') postCommand('getHistory');
        else if (tabId === 'branches') postCommand('getBranches');
        else if (tabId === 'stash') postCommand('getStashList');

        // Always update general status unless we just did it for the workspace
        if (tabId !== 'workspace') {
            postCommand('getStatus');
        }
    }

    // --- Rendering Functions ---
    function renderStatus(status) {
        const filesList = document.getElementById('files-list');
        const noChangesMessage = document.getElementById('no-changes-message');
        const fileTable = document.querySelector('#content-workspace .file-list');
        filesList.innerHTML = '';

        if (status.files.length === 0) {
            noChangesMessage.style.display = 'block';
            if (fileTable) fileTable.style.display = 'none';
        } else {
            noChangesMessage.style.display = 'none';
            filesList.style.display = '';
            status.files.forEach(file => {
                const row = document.createElement('tr');
                // A file's status is primarily determined by its state in the index (staging area).
                // If it's not in the index, we fall back to its state in the working directory.
                // The status codes from simple-git can have spaces, so we trim them.
                const fileStatus = (file.index.trim() || file.working_dir.trim());

                row.innerHTML = `
                    <td>${file.path}</td>
                    <td>${statusMap[fileStatus] || fileStatus}</td>
                    <td class="action-buttons">
                        <button class="diff-button" data-file-path="${file.path}" data-file-status="${fileStatus}">Diff</button>
                        <button class="discard-button" data-file-path="${file.path}">Discard</button>
                    </td>
                `;
                filesList.appendChild(row);
            });
        }
        document.getElementById('current-branch-display').textContent = status.current;

        const syncStatusEl = document.getElementById('branch-sync-status');
        let syncStatusHTML = '';
        if (status.ahead > 0) {
            syncStatusHTML += `<span>↑${status.ahead}</span>`;
        }
        if (status.behind > 0) {
            syncStatusHTML += ` <span class="behind">↓${status.behind}</span>`;
        }
        syncStatusEl.innerHTML = syncStatusHTML;
    }

    function renderHistory(history) {
        const historyList = document.getElementById('history-list');
        historyList.innerHTML = '';
        if (history.all.length === 0) {
            document.getElementById('no-history-message').style.display = 'block';
        } else {
            document.getElementById('no-history-message').style.display = 'none';
            history.all.forEach(commit => {
                const row = document.createElement('tr');

                let badgesHTML = '';
                if (commit.refs) {
                    const refs = commit.refs.split(', ');
                    const head = refs.filter(r => r.includes('HEAD ->')).map(r => `<span class="badge head-badge">${r.replace('HEAD ->', '').trim()}</span>`);
                    const tags = refs.filter(r => r.startsWith('tag: ')).map(r => `<span class="badge tag-badge">${r.replace('tag: ', '').trim()}</span>`);
                    badgesHTML = [...head, ...tags].join(' ');
                }

                row.innerHTML = `
                    <td>${commit.hash.substring(0, 7)}</td>
                    <td>${commit.author_name}</td>
                    <td>${commit.date}</td>
                    <td>${badgesHTML} ${commit.message}</td>
                    <td class="action-reset-button">
                        <button class="reset-button" data-hash="${commit.hash}">Reset</button>
                        <button class="tag-button-action" data-hash="${commit.hash}">Tag</button>
                    </td>
                `;
                historyList.appendChild(row);
            });
        }
    }

    function renderBranches(branches) {
        document.getElementById('current-branch-display').textContent = branches.current;
        const localBranchesList = document.getElementById('local-branches-list');
        const remoteBranchesList = document.getElementById('remote-branches-list');
        localBranchesList.innerHTML = '';
        remoteBranchesList.innerHTML = '';

        const localBranches = branches.all.filter(b => !b.startsWith('remotes/'));
        const remoteBranches = branches.all.filter(b => b.startsWith('remotes/'));
        
        localBranches.forEach(branch => {
            const li = document.createElement('li');
            let buttons = '';
            if (branch !== branches.current) {
                buttons = `
                    <button class="checkout-branch-button" data-branch="${branch}">Checkout</button>
                    <button class="merge-branch-button" data-branch="${branch}">Merge</button>
                    <button class="delete-local-branch-button" data-branch="${branch}">Delete</button>
                `;
            }
            li.innerHTML = `<span>${branch}</span><div>${buttons}</div>`;
            localBranchesList.appendChild(li);
        });

        remoteBranches.forEach(branch => {
            const li = document.createElement('li');
            li.innerHTML = `
                <span>${branch}</span>
                <div></div>
                    <button class="delete-remote-branch-button" data-branch="${branch}">Delete</button>
                </div>
            `;
            remoteBranchesList.appendChild(li);
        });
    }

    function renderStashList(stashes) {
        const stashList = document.getElementById('stash-list');
        stashList.innerHTML = '';

        if(!stashes.all || stashes.all.length === 0) {
            document.getElementById('no-stashes-message').style.display = 'block';
            document.querySelector('#content-stash .file-list').style.display = 'none';
        } else {
             document.getElementById('no-stashes-message').style.display = 'none';
             document.querySelector('#content-stash .file-list').style.display = '';
            stashes.all.forEach(stash => {
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td>${stash.ref}</td>
                    <td>${stash.message}</td>
                    <td class="action-buttons">
                        <button class="pop-stash-button" data-stash-ref="${stash.ref}">Pop</button>
                        <button class="drop-stash-button" data-stash-ref="${stash.ref}">Delete</button>
                    </td>
                `;
                stashList.appendChild(row);
            });
        }
    }

    // --- Event Listeners ---
    // Tab handling
    document.querySelectorAll('.tab-button').forEach(button => {
        button.addEventListener('click', (event) => {
            const tabId = event.currentTarget.id.replace('tab-', '');
            setActiveTab(tabId);
        });
    });

    // Button click delegation
    document.addEventListener('click', (event) => {
        const target = event.target;
        if (target.id === 'commit-button') postCommand('commit', { message: commitMessageTextarea.value });
        else if (target.id === 'commit-push-button') postCommand('commitAndPush', { message: commitMessageTextarea.value });
        else if (target.id === 'stash-all-button') postCommand('stashAll', { message: 'WIP' });
        else if (target.id === 'discard-all-button') postCommand('discardAll');
        else if (target.id === 'create-branch-button') postCommand('createBranch');
        else if (target.id === 'pull-button') postCommand('pull');
        else if (target.id === 'push-button') postCommand('push');
        
        // Use classList for delegated buttons
        const classList = target.classList;
        if (classList.contains('diff-button')) postCommand('viewDiff', { path: target.dataset.filePath, status: target.dataset.fileStatus });
        else if (classList.contains('discard-button')) postCommand('discardChanges', { path: target.dataset.filePath });
        else if (classList.contains('reset-button')) postCommand('resetToCommit', { hash: target.dataset.hash });
        else if (classList.contains('tag-button-action')) postCommand('createTag', { hash: target.dataset.hash });
        else if (classList.contains('checkout-branch-button')) postCommand('checkoutBranch', { branchName: target.dataset.branch });
        else if (classList.contains('merge-branch-button')) postCommand('mergeBranch', { branchName: target.dataset.branch });
        else if (classList.contains('delete-local-branch-button')) postCommand('deleteLocalBranch', { branchName: target.dataset.branch });
        else if (classList.contains('delete-remote-branch-button')) postCommand('deleteRemoteBranch', { branchName: target.dataset.branch });
        else if (classList.contains('pop-stash-button')) postCommand('popStash', { stashRef: target.dataset.stashRef });
        else if (classList.contains('drop-stash-button')) postCommand('dropStash', { stashRef: target.dataset.stashRef });
        else if (classList.contains('tag-button')) {
             const tagName = target.dataset.tag;
             const newPrefix = tagName + ': ';
             const prefixRegex = /^(\w+):\s*/;
             let messageBody = commitMessageTextarea.value;
             const match = messageBody.match(prefixRegex);
             if (match) {
                 messageBody = messageBody.substring(match[0].length);
             }
             commitMessageTextarea.value = newPrefix + messageBody;
             commitMessageTextarea.focus();
        }
    });

    // --- Message Handling ---
    window.addEventListener('message', event => {
        const message = event.data;
        switch (message.command) {
            case 'updateStatus':
                renderStatus(message.payload);
                break;
            case 'updateHistory':
                renderHistory(message.payload);
                break;
            case 'updateBranches':
                renderBranches(message.payload);
                break;
            case 'updateStashList':
                renderStashList(message.payload);
                break;
            case 'operationSuccess':
                renderStatus(message.payload.status);
                renderHistory(message.payload.history);
                renderBranches(message.payload.branches);
                if (message.payload.stashes) {
                    renderStashList(message.payload.stashes);
                }
                if (message.payload.activeTab) {
                    setActiveTab(message.payload.activeTab, false);
                }
                break;
            case 'commitDone':
                commitMessageTextarea.value = '';
                break;
        }
    });

    // --- Initial Load ---
    postCommand('webviewReady');
}()); 